package org.example;

import com.esotericsoftware.reflectasm.ConstructorAccess;
import com.esotericsoftware.reflectasm.FieldAccess;
import com.esotericsoftware.reflectasm.MethodAccess;

/*
<dependency>
    <groupId>com.esotericsoftware</groupId>
    <artifactId>reflectasm</artifactId>
    <version>1.11.9</version>
</dependency>
*/
public class App {
    public static void main(String[] args) {

        Dog dog = ConstructorAccess.get(Dog.class).newInstance();
        MethodAccess methodAccess = MethodAccess.get(Dog.class);
        methodAccess.invoke(dog, "hi");
        Object say = methodAccess.invoke(dog, "say");
        System.out.println(say);
        System.out.println("*******************************************");
        // 如果方法重载有同名方法的话，找到方法的索引执行方法，相比通过名称访问成员，索引的方式会更快
        int hiIndex = methodAccess.getIndex("hi", String.class);
        methodAccess.invoke(dog, hiIndex, "asdasdsad");
        System.out.println("*******************************************");

        // 使用 FieldAccess 反射 set/get 字段
        FieldAccess fieldAccess = FieldAccess.get(Dog.class);
        /*只能访问公共属性 Unable to find non-private field: name*/
        fieldAccess.set(dog, "name", "tommy");
        String name = (String) fieldAccess.get(dog, "name");
        System.out.println(name);

    }
}